package stringStudy;

/**
 * 题目：请实现一个函数，把字符串中的每个空格替换成“%20”。
 * 例如，输入“We are happy.”，则输出“We%20are%20happy.”。
 */
public class StringStudy02 {

    public static void main(String[] args) {
        String s = replaceSpace02("We are happy.");
        System.out.println(s);
    }

    //方法一：声明一个字符串，空间复杂度为o(n)
    public static String replaceSpace01(String s){
        if (s == null || "".equals(s))return s;
        StringBuilder sb = new StringBuilder(s);
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < sb.length(); i++){
            if (sb.charAt(i) == ' '){
                temp.append("%20");
            } else {
                temp.append(sb.charAt(i));
            }
        }
        return temp.toString();
    }
    //方法二：在字符串中进行修改,和删除有序数组中的重复元素道理相同，一个是扩张，一个是减少
    public static String replaceSpace02(String s){
        if (s == null || "".equals(s)) return s;
        StringBuilder builder = new StringBuilder(s);
        int oldLength = builder.length();
        int newLength = oldLength;
        for (int i = 0; i < oldLength; i++){
            if (builder.charAt(i)==' '){
                newLength += 2;
            }
        }
        builder.setLength(newLength);
        for (int i = oldLength-1, j = newLength -1; i >= 0 && j >=0;){
            if (builder.charAt(i) != ' '){
                builder.setCharAt(j--, builder.charAt(i--));
            } else {
                builder.setCharAt(j--, '0');
                builder.setCharAt(j--, '2');
                builder.setCharAt(j--, '%');
                i--;
            }
        }
        return builder.toString();
    }
}
